import dayjs from "dayjs";
import editForm from "../list/form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../hooks";
import { addDialog } from "@/components/ReDialog";
import { type FormItemProps, TrainingStatus, TrainingStatusText, TrainingLevelText, TrainingCategoryOptions } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h, toRaw, computed } from "vue";
import {
  getTrainingList,
  createTraining,
  updateTraining,
  deleteTraining,
  getTrainingDetail,
  updateTrainingStatus,
  enrollTraining,
  cancelTrainingEnroll
} from "@/api/training";

export function useTraining() {
  const form = reactive({
    title: "",
    category: "",
    instructorName: "",
    status: "",
    level: "",
    startTime: "",
    endTime: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle, tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号")
    },
    {
      label: "培训标题",
      prop: "title",
      minWidth: 180
    },
    {
      label: "培训分类",
      prop: "category",
      width: 120,
      cellRenderer: ({ row }) => {
        const categoryOption = TrainingCategoryOptions.find(item => item.value === row.category);
        return (
          <el-tag
            type="primary"
            effect="plain"
          >
            {categoryOption?.label || row.category}
          </el-tag>
        );
      }
    },
    {
      label: "讲师姓名",
      prop: "instructorName",
      width: 100
    },
    {
      label: "培训级别",
      prop: "level",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag
          type={row.level === 1 ? "success" : row.level === 2 ? "warning" : row.level === 3 ? "danger" : "info"}
          effect="plain"
        >
          {TrainingLevelText[row.level]}
        </el-tag>
      )
    },
    {
      label: "培训价格",
      prop: "price",
      width: 100,
      cellRenderer: ({ row }) => (
        <span style="color: #f56c6c; font-weight: bold;">¥{row.price}</span>
      )
    },
    {
      label: "报名人数",
      prop: "currentStudents",
      width: 100,
      cellRenderer: ({ row }) => (
        <span>
          <span style="color: #67c23a; font-weight: bold;">{row.currentStudents}</span>
          <span style="color: #909399;">/{row.maxStudents}</span>
        </span>
      )
    },
    {
      label: "培训时间",
      prop: "startTime",
      minWidth: 160,
      cellRenderer: ({ row }) => (
        <div>
          <div>{dayjs(row.startTime).format("YYYY-MM-DD HH:mm")}</div>
          <div style="color: #909399; font-size: 12px;">至 {dayjs(row.endTime).format("YYYY-MM-DD HH:mm")}</div>
        </div>
      )
    },
    {
      label: "培训地点",
      prop: "location",
      width: 120
    },
    {
      label: "培训状态",
      prop: "status",
      width: 100,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={TrainingStatus.PUBLISHED}
          inactive-value={TrainingStatus.DRAFT}
          active-text="已发布"
          inactive-text="草稿"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 130,
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === TrainingStatus.DRAFT ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.title
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === TrainingStatus.DRAFT ? "停用" : "启用"}${row.title}`, {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status =
          row.status === TrainingStatus.DRAFT ? TrainingStatus.PUBLISHED : TrainingStatus.DRAFT;
      });
  }

  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除培训<strong style='color:var(--el-color-primary)'>${row.title}</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        message(`已删除培训${row.title}`, { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleDetail(row) {
    // 跳转到培训详情页面
    window.location.href = `#/training/detail?id=${row.id}`;
  }

  function handleEnroll(row) {
    ElMessageBox.confirm(
      `确认要报名参加培训<strong style='color:var(--el-color-primary)'>${row.title}</strong>吗?`,
      "培训报名",
      {
        confirmButtonText: "确定报名",
        cancelButtonText: "取消",
        type: "info",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        message(`已成功报名培训${row.title}`, { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    // 使用模拟数据
    const mockData = generateMockData();
    dataList.value = mockData;
    pagination.total = mockData.length;
    
    setTimeout(() => {
      loading.value = false;
    }, 500);
    
    // 实际开发时使用真实接口
    // const { result } = await getTrainingList(toRaw(form));
    // dataList.value = result.lists;
    // pagination.total = result.total;
    // pagination.pageSize = result.pageSize;
    // pagination.currentPage = result.currentPage;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}培训`,
      props: {
        formInline: {
          id: row?.id ?? "",
          title: row?.title ?? "",
          description: row?.description ?? "",
          category: row?.category ?? "",
          instructorId: row?.instructorId ?? 0,
          instructorName: row?.instructorName ?? "",
          maxStudents: row?.maxStudents ?? 20,
          currentStudents: row?.currentStudents ?? 0,
          price: row?.price ?? 0,
          originalPrice: row?.originalPrice ?? 0,
          startTime: row?.startTime ?? "",
          endTime: row?.endTime ?? "",
          duration: row?.duration ?? 0,
          location: row?.location ?? "",
          address: row?.address ?? "",
          status: row?.status ?? TrainingStatus.DRAFT,
          level: row?.level ?? 1,
          tags: row?.tags ?? "",
          coverImage: row?.coverImage ?? "",
          content: row?.content ?? "",
          requirements: row?.requirements ?? "",
          objectives: row?.objectives ?? "",
          schedule: row?.schedule ?? "",
          materials: row?.materials ?? "",
          certificate: row?.certificate ?? false,
          remark: row?.remark ?? "",
          createTime: row?.createTime ?? "",
          updateTime: row?.updateTime ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了培训${curData.title}`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发时这里会调用新增接口
              chores();
            } else {
              // 实际开发时这里会调用编辑接口
              chores();
            }
          }
        });
      }
    });
  }

  /** 生成模拟数据 */
  function generateMockData() {
    const mockData = [];
    const titles = ["羽毛球基础培训", "乒乓球进阶课程", "网球专业训练", "篮球技巧提升", "游泳入门教学"];
    const categories = ["badminton", "table-tennis", "tennis", "basketball", "swimming"];
    const instructors = ["张教练", "李老师", "王指导", "赵教练", "钱老师"];
    const locations = ["体育馆A", "训练场B", "游泳馆C", "篮球场D", "网球场E"];

    for (let i = 1; i <= 5; i++) {
      const startTime = dayjs().add(i, 'week').format('YYYY-MM-DD 09:00:00');
      const endTime = dayjs().add(i, 'week').add(2, 'hour').format('YYYY-MM-DD 11:00:00');
      
      mockData.push({
        id: i,
        title: titles[i - 1],
        description: `这是${titles[i - 1]}的详细描述，包含了培训的主要内容和目标。`,
        category: categories[i - 1],
        instructorId: i,
        instructorName: instructors[i - 1],
        maxStudents: 20 + i * 5,
        currentStudents: i * 3,
        price: 100 + i * 50,
        originalPrice: 150 + i * 50,
        startTime,
        endTime,
        duration: 2,
        location: locations[i - 1],
        address: `体育中心${locations[i - 1]}详细地址${i}号`,
        status: i <= 3 ? TrainingStatus.PUBLISHED : TrainingStatus.DRAFT,
        level: (i % 4) + 1,
        tags: `标签${i},培训,运动`,
        coverImage: "",
        content: `培训内容详情${i}，包含理论学习和实践训练。`,
        requirements: `报名要求${i}：身体健康，无运动禁忌。`,
        objectives: `培训目标${i}：掌握基本技能，提升运动水平。`,
        schedule: `课程安排${i}：理论课1小时，实践课1小时。`,
        materials: `培训材料${i}：教学视频，练习手册。`,
        certificate: i % 2 === 1,
        remark: `备注信息${i}`,
        createTime: dayjs().subtract(i, 'day').format('YYYY-MM-DD HH:mm:ss'),
        updateTime: dayjs().subtract(i - 1, 'day').format('YYYY-MM-DD HH:mm:ss')
      });
    }
    return mockData;
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleDetail,
    handleEnroll,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}